package com.retailshop.shopuser.WapUserController;

import com.retailshop.shopuser.common.MessageConstants;
import com.retailshop.shopuser.common.Response;
import com.retailshop.shopuser.common.StringUtil;
import com.retailshop.shopuser.common.UserLoginToken;
import com.retailshop.shopuser.entity.HttpRequestConfig;
import com.retailshop.shopuser.entity.SignIn;
import com.retailshop.shopuser.entity.SignVoucher;
import com.retailshop.shopuser.entity.SignVoucherInfo;
import com.retailshop.shopuser.service.SignInService;
import com.retailshop.shopuser.service.SignVoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/wap")
public class SignInController {

    @Autowired
    SignInService signInService;
    @Autowired
    SignVoucherService signVoucherService;


    /**
     * 查询用户签到天数
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getSignInfo")
    public Response getSignInfo(HttpServletRequest request) {
        int userNoId = 0;
        int signDays = 1;
        String time = null;
        Calendar c = Calendar.getInstance();
        int days = c.get(Calendar.DAY_OF_MONTH);
        int month = c.get(Calendar.MONTH) + 1;
        int maxDay = 0;
        int signMonth = 0;
        int signDay = 0;
        String userNoIds = request.getParameter("userNoId");//用户
        if (userNoIds == null || userNoIds == "" || !StringUtil.isNumeric(userNoIds)) {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }
        SignVoucherInfo signVoucherInfo=null;
        userNoId = Integer.parseInt(userNoIds);
        SignIn signIns = signInService.selectByUserNoId(userNoId);

        if (signIns != null) {
            signDays = signIns.getSignDays();
            time = signIns.getSignInTime();
            if (time != null) {
                String[] arr = time.split("-");
                signMonth = Integer.parseInt(arr[0]);
                signDay = Integer.parseInt(arr[1]);
            }


            if (signMonth == month) {//同月
                int date = days - signDay;
                if (date >= 2) {//大于1天 更新用户的签到天数
                    updateSignDays(userNoId, 1);
                    System.out.println("--2--->");
                    signDays = 1;
                }

            } else {//次月
                maxDay = c.getActualMaximum(c.DATE - 1);
                int date = maxDay - signDay;
                if (date >= 2) {//大于1天
                    updateSignDays(userNoId, 1);
                    signDays = 1;
                    System.out.println("--m-->");
                }

            }

        }


        if (signDays > 1 && signDays < 15) {//第一天

            signDays = signDays;

        } else if (signDays >15) {//大于第15天
            signDays = 15;//15天以后的代金券就是按15天的代金券返回
//            updateSignDays(userNoId, signDays);
        }


//        SignIn signIn = signInService.selectSignInByUsenoId(userNoId, signDays);
        signVoucherInfo = signInService.selectSignInByUsenoId(userNoId, signDays);
        signVoucherInfo.setVoucher(signVoucherInfo.getVoucher());
        SignIn signIn=null;
        if (signVoucherInfo== null) {
            signVoucherInfo  = new SignVoucherInfo ();
            return new Response(MessageConstants.MSG_SUCCESS, signVoucherInfo, 0, "", request);
        }
        return new Response(MessageConstants.MSG_SUCCESS, signVoucherInfo, 0, "", request);
    }


    private void updateSignDays(int userNoId, int i) {
        SignIn signIn = new SignIn();
        signIn.setSignDays(i);
        signIn.setUserNoId(userNoId);
        int row = signInService.updateSignDays(signIn);
    }



    /**
     * 用户签到 ----->不传入代金券
     * @param request
     * @return
     */

//    @UserLoginToken
    @ResponseBody
    @RequestMapping("/signIn")
    public Response signIn(HttpServletRequest request) {
        String userNoIds = request.getParameter("userNoId");
//        String vouchers = request.getParameter("voucher");
        int userNoId = 0;
        if (userNoIds == null || userNoIds == "" || !StringUtil.isNumeric(userNoIds) ) {
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
        }
        double voucher = 0.00;
        Calendar c = Calendar.getInstance();
        int days = c.get(Calendar.DAY_OF_MONTH);
        int month = c.get(Calendar.MONTH) + 1;
//        voucher = Double.parseDouble(vouchers);
        userNoId = Integer.parseInt(userNoIds);
        SignIn signIn = signInService.selectByUserNoId(userNoId);
        SignIn signIn1 = new SignIn();
        int alreadySignDays = 1;
int days1=0;
        if (signIn == null) {   //第一次签名
            signIn1.setUserNoId(userNoId);
            signIn1.setSignDays(1);
            signIn1.setSignInTime(month + "-" + days);
            signIn1.setSignState("1");
            signIn1.setDays(1);
            int row = signInService.insertSelective(signIn1);
            days1=1;
            return getResponse(request, userNoIds, signIn1, alreadySignDays, row);


        } else {
            //判断当天是否签到
            String signTime = signIn.getSignInTime();
            int signMonth = 0;
            int signDay = 0;
            if (signTime != null) {
                String[] arr = signTime.split("-");
                signMonth = Integer.parseInt(arr[0]);
                signDay = Integer.parseInt(arr[1]);
            }

            if (month == signMonth && days == signDay) {
                return new Response(MessageConstants.SIGN, null, 0, "", request);
            }
            alreadySignDays = signIn.getSignDays();
            signIn1 = new SignIn();
            signIn1.setUserNoId(userNoId);
            signIn1.setSignInTime(month + "-" + days);
            signIn1.setSignState("1");
            signIn1.setSignInId(signIn.getSignInId());

            //判断签到是否间隔一天
            if (days - signDay >= 2) {//间隔一天
                signIn1.setSignDays(1);
                signIn1.setDays(1);
                days1=1;
            } else if (alreadySignDays >= 15) {
                signIn1.setSignDays(signIn.getSignDays() + 1);
                signIn1.setDays(15);
                days1=15;
            } else {
                signIn1.setSignDays(signIn.getSignDays() + 1);
                signIn1.setDays(signIn.getSignDays() + 1);
                days1=signIn.getSignDays() + 1;
            }

            int row1 = signInService.updateByPrimaryKeySelective(signIn1);
            return getResponse(request, userNoIds, signIn1,days1, row1);

        }
    }

    private Response getResponse(HttpServletRequest request, String userNoIds, SignIn signIn1, int alreadySignDays, int row1) {
        double voucher=0.00;
        if (row1 > 0) {
            SignVoucher signVoucher = signVoucherService.selectVoucherByDays(alreadySignDays);
            if(signVoucher!=null){
                voucher = signVoucher.getVoucher();
                System.out.println("---s--->"+voucher);
            }
            givePresent(userNoIds, voucher + "");
            return new Response(MessageConstants.MSG_SUCCESS, signIn1, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
        }
    }

    private void givePresent(String userNoIds, String vouchers) {
        System.out.println("---v-->"+vouchers);
        RestTemplate restTemplate = new RestTemplate();
        String url = HttpRequestConfig.finaceServerUrl + "/wap/Add";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userNoId", userNoIds);
        map.add("classify", "3");
        map.add("amount", vouchers);
        map.add("remark", "签到获得");
        HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(map, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);
    }


    /**
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getVoucherList")
    public Response getVoucherList(HttpServletRequest request) {
        List<SignVoucher> signVoucherList = signVoucherService.selectList();
        return new Response(MessageConstants.MSG_SUCCESS, signVoucherList, 0, "", request);
    }


}
